package leetcode.code1451;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import leetcode.IDebug;

public class Solution implements IDebug {

	public String arrangeWords(String text) {
		text = (char) (text.charAt(0) - 'A' + 'a') + text.substring(1);
		String[] words = text.split(" ");
		Map<Integer, List<String>> map = new HashMap<>();
		Set<Integer> lens = new HashSet<>();
		for (String w : words) {
			int len = w.length();
			if (lens.add(len)) {
				map.computeIfAbsent(len, key -> {
					List<String> list = new ArrayList<>();
					list.add(w);
					return list;
				});
			} else {
				map.computeIfPresent(len, (a, b) ->
				{
					b.add(w);
					return b;
				});
			}
		}
		List<Integer> lenList = new ArrayList<>(lens);
		Collections.sort(lenList);
		StringJoiner sj = new StringJoiner(" ");
		for (int i = 0; i < lenList.size(); i++) {
			List<String> list = map.get(lenList.get(i));
			for (String word : list) {
				sj.add(word);
			}
		}
		String ans = sj.toString();
		return (char) (ans.charAt(0) - 'a' + 'A') + ans.substring(1);
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
